// 设置定时开关机
import React from 'react';
import { View, Text, Image, TouchableOpacity, AsyncStorage } from 'react-native';
import { TitleBar } from 'miot/ui';
import Switch from 'miot/ui/Switch';
import MHDatePicker from 'miot/ui/MHDatePicker';
import Separator from 'miot/ui/Separator';
import pxSize from '../util/pxSize';
import styles from '../styles/timeSetUPStyl';
import TimeOut from '../util/time';
import MainPage from '../MainPage';
export default class TimeSetPage extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      startVisible: false,
      colseVisible: false,
      startTimes: '',
      colseTimes: '',
      startBoole: false,
      colseBoole: false,
      closeDisabled: true,
      startDisabled: true
    };
    this.writeStringStart = '';
    this.writeStringColse = '';
  }
  UNSAFE_componentWillMount() {
    AsyncStorage.getItem('StartTime', (err, result) => {
      console.log('StartTime', result);
      result ? this.setState({ startTimes: result, startDisabled: false }) : this.setState({ startTimes: '未设置' });
    });
    AsyncStorage.getItem('ColseTime', (err, result) => {
      console.log('ColseTime', result);
      result ? this.setState({ colseTimes: result, closeDisabled: false }) : this.setState({ colseTimes: '未设置' });
    });
    AsyncStorage.getItem('StartBoole', (err, result) => {
      console.log('StartBoole', result);
      result === "true" ? this.setState({ startBoole: true }) : this.setState({ startBoole: false });
    });
    AsyncStorage.getItem('ColseBoole', (err, result) => {
      console.log('ColseBoole', result);
      result == "true" ? this.setState(() => ({ colseBoole: true })) : this.setState(() => ({ colseBoole: false }));
    });
    AsyncStorage.getItem('writeStringStart', (err, result) => {
      console.log('writeStringStart', result);
      result ? this.writeStringStart = result : '';
    });

    AsyncStorage.getItem('writeStringColse', (err, result) => {
      console.log('writeStringColse', result);
      result ? this.writeStringColse = result : '';
    });
  }

  render() {
    const { startTimes,
      colseTimes } = this.state;
    return (
      <View style={styles.container}>
        <TitleBar
          type="dark"
          title="定时设置"
          style={styles.titleBar}
          onPressLeft={() => { this.props.navigation.goBack(); }}
        />
        {/* 确定按钮  */}
        <View style={styles.button}>

          <TouchableOpacity onPress={this.handleTime.bind(this)}>
            <Text style={{ fontSize: pxSize(15), color: "#fff" }}>确定</Text>
          </TouchableOpacity>
        </View>

        <View>
          <View style={styles.list_item_father}>
            <TouchableOpacity
              onPress={() => this.setState(() => ({ startVisible: true }))}
              style={{ flexGrow: 1 }}
            >
              <View style={styles.list_item}>
                <Text style={{ fontSize: pxSize(17), color: "black" }}>开启时间</Text>
                <Text style={{ marginTop: pxSize(3), fontSize: pxSize(14) }}>{startTimes}</Text>
              </View>
            </TouchableOpacity>
            <Switch
              disabled={this.state.startDisabled}
              style={{ width: pxSize(60), height: pxSize(30) }}
              onTintColor="#4A8EFD"
              tintColor="#ccc"
              value={this.state.startBoole}
              onValueChange={(value) => this.startChange(value)}
            />
          </View>
          <Separator />
        </View>
        <View>
          <View style={styles.list_item_father}>
            <TouchableOpacity
              style={{ flexGrow: 1 }}
              onPress={() => this.setState(() => ({ colseVisible: true }))}
            >
              <View style={styles.list_item}>
                <Text style={{ fontSize: pxSize(17), color: "black" }}>关闭时间</Text>
                <Text style={{ marginTop: pxSize(3), fontSize: pxSize(14) }}>{colseTimes}</Text>
              </View>
            </TouchableOpacity>
            <Switch
              disabled={this.state.closeDisabled}
              style={{ width: pxSize(60), height: pxSize(30) }}
              onTintColor="#4A8EFD"
              tintColor="#ccc"
              value={this.state.colseBoole}
              onValueChange={(value) => this.closeChange(value)}
            />
          </View>
          <Separator />
        </View>
        <MHDatePicker
          visible={this.state.startVisible}
          title="开启时间"
          type={MHDatePicker.TYPE.TIME24}
          onDismiss={(_) => this.setState(() => ({ startVisible: false }))}
          onSelect={this.onSelectStartTime.bind(this)}
        />

        <MHDatePicker
          visible={this.state.colseVisible}
          title="关闭时间"
          type={MHDatePicker.TYPE.TIME24}
          onDismiss={(_) => {
            console.log('_ :>> ', 123123);
            this.setState(() => ({ colseVisible: false }));
          } }
          onSelect={this.onSelectColseTime.bind(this)}
        />

      </View>
    );


  }
  closeChange(value) {
    
    if (value) {
      MainPage.bleWrite(this.writeStringColse);
     
    } else {
      MainPage.bleWrite('B85102ffffff8B');
    }
    AsyncStorage.setItem("ColseBoole", value.toString());
    
    
  }
  startChange(value) {
    
    if (value) {
      MainPage.bleWrite(this.writeStringStart);
    } else {
      MainPage.bleWrite('B85101ffffff8B');
    }
    AsyncStorage.setItem("StartBoole", value.toString());
      
    
    
   
  }
  /**
  * 
  * @param {int} setTimes 设置时间总秒数 
  */
  computeSeconds(setTimes) {
    const nowSeconds = TimeOut.getAllSeconds(new Date());
    const setSeconds = TimeOut.getAllSeconds(setTimes);
    if (setSeconds < nowSeconds) {
      const seconds = 24 * 60 * 60 - nowSeconds + setSeconds;
      return seconds;
    }
    const seconds = setSeconds - nowSeconds;
    return seconds;
  }
  // 拼接写的字符串
  spliceString(seconds) {
    // let writeString = seconds.toString(16);
    let writeString = seconds;
    console.log("TimeSetPage -> spliceString -> writeString", writeString);
    // const secondLength = seconds.toString(16).length;
    const secondLength = seconds.toString().length;
    for (let i = 0; i < 6 - secondLength; i++) {
      writeString = `0${ writeString }`;
    }
    return writeString;
  }
  // 设置开机时间
  onSelectStartTime(res) {
    const { rawString, date } = res;
    const allSeconds = this.computeSeconds(date);
    this.writeStringStart = `B85101${ this.spliceString(allSeconds) }8B`;
    console.log('开机时间 :>> ', this.writeStringStart, this.spliceString(allSeconds));
    MainPage.bleWrite(this.writeStringStart);
    this.setState({
      startTimes: rawString,
      startBoole: true,
      startDisabled: false
    });
    AsyncStorage.setItem("StartBoole", true.toString());
    AsyncStorage.setItem("StartTime", rawString);
    AsyncStorage.setItem("writeStringStart", this.writeStringStart);
  }
  // 设置关机时间
  onSelectColseTime(res) {
    console.log('resresresresres :>> ', res);
    const { rawString, date } = res;
    const allSeconds = this.computeSeconds(date);
    this.writeStringColse = `B85102${ this.spliceString(allSeconds) }8B`;
    console.log('关机时间 :>> ', this.writeStringColse, this.spliceString(allSeconds));
    MainPage.bleWrite(this.writeStringColse);
    this.setState({
      colseTimes: rawString,
      colseBoole: true,
      closeDisabled: false
    });
    AsyncStorage.setItem("ColseBoole", true.toString());
    AsyncStorage.setItem("ColseTime", rawString);
    AsyncStorage.setItem("writeStringColse", this.writeStringColse);
  }
  handleTime() {
    const {
      startTimes,
      colseTimes
    } = this.state;
    /*   startTimes === '未设置' ? MainPage.bleWrite('B85101ffffff8B') : null
  setTimeout(() => {
   colseTimes === '未设置' ? MainPage.bleWrite('B85102ffffff8B') : null
  }, 5000) */

    // MainPage.bleWrite('B85101ffffff8B')

    this.props.navigation.navigate('MainPage',
      /* {
    time: (startTimes === '未设置' ? '' : `${startTimes}开启  `) + (colseTimes === '未设置' ? '' : `${colseTimes}关闭`)
   } */
    );
  }

}



